package com.dongdongshop.mq;

import com.alibaba.fastjson.JSONObject;
import com.dongdongshop.mapper.TbSeckillOrderMapper;
import com.dongdongshop.pojo.TbSeckillGoods;
import com.dongdongshop.pojo.TbSeckillOrder;
import com.dongdongshop.service.OrderService;
import com.dongdongshop.service.ScoreAccountService;
import com.dongdongshop.util.IdWorker;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Date;

@Component
@RocketMQMessageListener(consumerGroup = "seckill-consumer-group",topic = "seckill-topic")
public class SeckilConsumer implements RocketMQListener<String> {
    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private IdWorker idWorker;

    @Autowired
    private TbSeckillOrderMapper tbSeckillOrderMapper;

    //没有ACK 了， 也就是说这种方式不适合生产环境使用
    //一旦重写了prepareStart方法，此方法失效，但是必须实现RocketMQListener接口
    @Override
    public void onMessage(String message) {
        JSONObject jsonObject = JSONObject.parseObject(message);
        Integer goodsId = (Integer) jsonObject.get("goodsId");
        String username = (String) jsonObject.get("username");

        //生成订单
        Long orderId = idWorker.nextId();
        TbSeckillOrder seckillOrder = new TbSeckillOrder();
//        seckillOrder.setTransactionId(); 交易流水号
//        seckillOrder.setReceiver(); 收货人
//        seckillOrder.setPayTime(); 支付时间
        TbSeckillGoods seckillGoods = (TbSeckillGoods) redisTemplate.boundHashOps("seckill_goods_list").get(goodsId.longValue());
        seckillOrder.setCreateTime(new Date());
        seckillOrder.setMoney(seckillGoods.getCostPrice());
        seckillOrder.setSeckillId(goodsId.longValue());
        seckillOrder.setStatus("0");
        seckillOrder.setSellerId(seckillGoods.getSellerId());//商家id
        seckillOrder.setUserId(username);
        seckillOrder.setId(orderId);
        //seckillOrder.setReceiverMobile();收货人手机号
        //seckillOrder.setReceiverAddress(); 收货地址
        tbSeckillOrderMapper.insertSelective(seckillOrder);

        //将订单id存放到redis中(因为是异步生成的订单，所以无法直接返回订单号）
        redisTemplate.boundHashOps("seckill-order-id").put(username,orderId);
    }
}
